#include "triangle.h"

#include <stdio.h>
#include <stdlib.h>

Circle * circumcircle(Triangle * t){
   Circle * c = (Circle *)malloc(sizeof(Circle));
   Point * middiff = newPoint();
   Point * u = newPoint();
   Point * v = newPoint();
   double tt = 0.0;
   c->s = newPoint();
   middiff->x = (t->c->x - t->a->x)/2;
   middiff->y = (t->c->y - t->a->y)/2;

   u->x = t->a->y - t->b->y;
   u->y = t->b->x - t->a->x;

   v->x = t->c->x - t->b->x;
   v->y = t->c->y - t->b->y;

   tt = dot(middiff, v)/dot(u, v);

   c->s->x = (tt * u->x + (t->a->x + t->b->x)/2);
   c->s->y = (tt * u->y + (t->a->y + t->b->y)/2);

   c->r = distance(c->s, t->a);

   return c;
}

Triangle * newTriangle(){
	Triangle * t = (Triangle *)malloc(sizeof(Triangle));
	t->a = (Point *)malloc(sizeof(Point));
	t->b = (Point *)malloc(sizeof(Point));
	t->c = (Point *)malloc(sizeof(Point));
	t->next = NULL;
	return t;
}

void freeTriangle(Triangle * t){
	if(t != NULL)
		free(t);
}

void printTriangle(Triangle * t){
	if(t != NULL)
		printf("Triangle[a=(%g, %g), b=(%g, %g), c=(%g, %g)]\n", t->a->x, t->a->y, t->b->x, t->b->y, t->c->x, t->c->y);
	else
		printf("Triangle[NULL]\n");
}

int compareTriangle(Triangle * t1, Triangle * t2){
	int equal = 0;
	if(compare(t1->a, t2->a) == 0)
		equal++;
	if(compare(t1->a, t2->b) == 0)
		equal++;
	if(compare(t1->a, t2->c) == 0)
		equal++;
	if(compare(t1->b, t2->a) == 0)
		equal++;
	if(compare(t1->b, t2->b) == 0)
		equal++;
	if(compare(t1->b, t2->c) == 0)
		equal++;
	if(compare(t1->c, t2->a) == 0)
		equal++;
	if(compare(t1->c, t2->b) == 0)
		equal++;
	if(compare(t1->c, t2->c) == 0)
		equal++;

	if(equal == 3)
		return 1;
	else
		return 0;
}

int triangleContainsPoint(Triangle * t, Point * p){
	if(compare(t->a, p) == 0 || compare(t->b, p) == 0 || compare(t->c, p) == 0)
		return 1;
	return 0;
}

/*
int main(){
	circle * c;
	triangle * t = newTriangle();
	t->a->x = 1.0;
	t->a->y = 0.0;
	t->b->x = 0.0;
	t->b->y = 1.0;
	t->c->x = -1.0;
	t->c->y = 0.0;

	c = circumcircle(t);
	printf("center = [%g; %g]\n", c->s->x, c->s->y);
	printf("r = %g\n", c->r);

	return 0;
}*/
